Component({
  // behaviors: ['wx://component-export'],
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
    dates: [],
    weekDays: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    activeTimes: {},
  },
  lifetimes: {
    attached: function () {},
    ready: function () {
      this.queryDate();
      // 组件实例进入页面节点树且所在页面也已渲染完成时执行
    },
    detached: function () {
      // 组件实例离开页面节点树时执行
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async queryDate() {
      try {
        const res = await getApp().request({
          path: "/s/t/getDayByTeacherId",
          method: "GET",
          data: {
            tid: "179132900338434048",
          },
        });
        this.pickerInit(res || {});
      } catch {}
    },
    // pickerInit(data) {
    //   function datesEqual(date1, date2) {
    //     return (
    //       date1.getFullYear() === date2.getFullYear() &&
    //       date1.getMonth() === date2.getMonth() &&
    //       date1.getDate() === date2.getDate()
    //     );
    //   }
    //   const today = new Date();
    //   const nextMonthLastDay = new Date(
    //     today.getFullYear(),
    //     today.getMonth() + 2,
    //     0
    //   );

    //   const weekDays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

    //   let thisMonthDates = [];
    //   let nextMonthDates = [];
    //   let currentDay = new Date(today);
    //   const daysToAddBefore = today.getDay() === 0 ? 6 : today.getDay() - 1;

    //   // 先添加空对象，确保从周一开始
    //   for (let i = 0; i < daysToAddBefore; i++) {
    //     thisMonthDates.push(null);
    //   }

    //   let dayOfWeekCounter = daysToAddBefore; // 初始星期几计数器

    //   // 从今天的日期开始渲染，直到下个月底
    //   while (
    //     currentDay <= nextMonthLastDay ||
    //     (datesEqual(currentDay, nextMonthLastDay) && dayOfWeekCounter % 7 !== 0)
    //   ) {
    //     const dateStr = `${currentDay.getDate().toString().padStart(2, "0")}`;
    //     const dayOfWeek = weekDays[dayOfWeekCounter % 7];
    //     const monthStr = `${currentDay.getMonth() + 1}`.padStart(2, "0");
    //     const year = currentDay.getFullYear();
    //     const date = `${year}-${monthStr}-${dateStr}`;
    //     const isFreeTime = Object.keys(data).includes(date);

    //     const dateItem = {
    //       month: monthStr,
    //       date: dateStr,
    //       dayOfWeek: dayOfWeek,
    //       year: year,
    //       timeslots: isFreeTime ? data[date] : [], // 这里可以动态生成时间段
    //     };
    //     // 根据当前日期的月份决定添加到哪个数组
    //     if (currentDay.getMonth() === today.getMonth()) {
    //       thisMonthDates.push(dateItem);
    //     } else {
    //       nextMonthDates.push(dateItem);
    //     }

    //     // 更新星期几的计数器
    //     dayOfWeekCounter++;

    //     // 增加一天
    //     currentDay.setDate(currentDay.getDate() + 1);
    //   }
    //   console.log(thisMonthDates, nextMonthDates, "thisMonthDates");
    //   // 渲染时考虑星期几的对齐，现在每7个元素为一行
    //   const renderThisMonthDates = [];
    //   for (let i = 0; i < thisMonthDates.length; i += 7) {
    //     renderThisMonthDates.push(thisMonthDates.slice(i, i + 7));
    //   }

    //   const renderNextMonthDates = [];
    //   for (let i = 0; i < nextMonthDates.length; i += 7) {
    //     renderNextMonthDates.push(nextMonthDates.slice(i, i + 7));
    //   }

    //   // 整合成一个数组对象，每个对象包含一个月的日期数组和月份信息
    //   const monthsData: any = [
    //     {
    //       month: `${today.getFullYear()}-${(today.getMonth() + 1)
    //         .toString()
    //         .padStart(2, "0")}`, // 确保月份为两位数字
    //       dates: renderThisMonthDates,
    //     },
    //     {
    //       month: `${nextMonthLastDay.getFullYear()}-${(
    //         nextMonthLastDay.getMonth() + 1
    //       )
    //         .toString()
    //         .padStart(2, "0")}`, // 确保月份为两位数字
    //       dates: renderNextMonthDates,
    //     },
    //   ];
    //   console.log(monthsData, "monthsData");
    //   this.setData({
    //     dates: monthsData,
    //   });
    //   },
    pickerInit(data) {
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth() + 1;
      const nextMonth = (currentMonth % 12) + 1;
      const nextYear = currentMonth === 12 ? currentYear + 1 : currentYear;

      // 生成日期的函数，返回包含所有所需字段的对象数组
      function generateDates(year, month) {
        let dates = [];
        let endDate = new Date(year, month, 0).getDate() + 1; // 获取下个月的第0天，即本月的最后一天，然后+1为了循环结束
        const weekDays = [
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六",
          "周日",
        ];

        for (let day = 1; day < endDate; day++) {
          let dateObj = new Date(year, month - 1, day);
          const dayIndex = (dateObj.getDay() + 6) % 7; // 调整索引以从周一（0）开始
          const monthStr = month.toString().padStart(2, "0");
          const dateStr = dateObj.getDate().toString().padStart(2, "0");
          const date = `${year}-${monthStr}-${dateStr}`;
          const isFreeTime = Object.keys(data).includes(date);
          dates.push({
            month: monthStr,
            date: dateStr,
            dayOfWeek: weekDays[dayIndex], // 使用调整后的dayIndex
            year: year,
            timeslots: isFreeTime ? data[date] : [], // 假设没有具体的空闲时间数据，这里留空
          });
        }
        return dates;
      }

      // 生成本月的剩余日期
      const thisMonthDates = generateDates(currentYear, currentMonth);
      // 裁剪到从今天开始
      thisMonthDates.splice(0, today.getDate() - 1);

      // 生成下个月的日期
      const nextMonthDates = generateDates(nextYear, nextMonth);

      // 按周分组日期
      function groupDatesByWeek(dates) {
        let groupedDates = [];
        let currentWeek = [];
        let firstMondayIndex = -1;

        // 遍历所有日期以找到第一个周一的索引
        for (let i = 0; i < dates.length; i++) {
          if (dates[i].dayOfWeek === "周一") {
            firstMondayIndex = i;
            break;
          }
        }

        // 处理第一个周一之前的数据
        if (firstMondayIndex > 0) {
          let firstWeek = dates.slice(0, firstMondayIndex);
          const firstWeekLength = firstWeek.length;
          // 在前面补充null值直到周一
          for (let i = 0; i < 7 - firstWeekLength; i++) {
            firstWeek.unshift(null); // 在数组开头添加null
          }
          // 将这个“不完整”的周添加到结果数组中
          groupedDates.push(firstWeek);
          currentWeek = []; // 重置当前周数组以开始新的周
        }

        // 从第一个周一开始，按周分组
        for (let i = firstMondayIndex; i < dates.length; i++) {
          currentWeek.push(dates[i]);
          // 当当前周达到7个日期或到达数组末尾时，将其添加到结果数组中
          if (
            currentWeek.length === 7 ||
            (i === dates.length - 1 && currentWeek.length > 0)
          ) {
            groupedDates.push(currentWeek);
            currentWeek = []; // 重置当前周数组
          }
        }

        // 如果最后一个周不完整（且不是空数组），则也将其添加到结果数组中
        if (currentWeek.length > 0) {
          groupedDates.push(currentWeek);
        }

        return groupedDates;
      }
      const renderThisMonthDates = groupDatesByWeek(thisMonthDates);
      const renderNextMonthDates = groupDatesByWeek(nextMonthDates);

      // 整合为monthsData
      const monthsData: any = [
        {
          month: `${currentYear}-${currentMonth.toString().padStart(2, "0")}`,
          dates: renderThisMonthDates,
        },
        {
          month: `${nextYear}-${nextMonth.toString().padStart(2, "0")}`,
          dates: renderNextMonthDates,
        },
      ];
      this.setData({
        dates: monthsData,
      });
    },
    handleTimewithDate(event: any) {
      const { year, month, date } = event.currentTarget.dataset.it; // 假设数据集中包含日期和时间
      const times = event.currentTarget.dataset.times;
      let updatedActiveTimes: any = { ...this.data.activeTimes }; // 深拷贝现有状态
      const isEmpty = Object.keys(updatedActiveTimes).length === 0;
      // 如果当前时间已经存在，则清除它；否则，设置为活动时间
      if (isEmpty) {
        updatedActiveTimes[`${year}-${month}-${date}`] = times;
      } else {
        updatedActiveTimes = {};
        updatedActiveTimes[`${year}-${month}-${date}`] = times;
      }
      console.log(updatedActiveTimes, "updatedActiveTimes");
      this.setData({
        activeTimes: updatedActiveTimes,
      });
    },
    handleClear() {
      this.setData({
        activeTimes: {},
      });
    },
  },
});
